package com.woniuxy.microsysserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microsysserver.bean.AdminInfo;
import com.woniuxy.microsysserver.bean.OptInfo;
import com.woniuxy.microsysserver.mapper.OptMapper;
import com.woniuxy.microsysserver.service.IAdminService;
import com.woniuxy.microsysserver.service.IOutService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OutServiceImpl implements IOutService {
    @Resource
    OptMapper optMapper;
    @Resource
    RocketMQTemplate rocketMQTemplate;
    @Resource
    IAdminService adminService;
    @Override
    public void sendOut(Integer id,String TxNo,String IpAddr) {
        //操作的管理员
        AdminInfo admin = adminService.findById(id);
        //管理员到string
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("admin",admin);
        jsonObject.put("no", TxNo);
        jsonObject.put("ip", IpAddr);
        String jsonString = jsonObject.toJSONString();
        //生成message类型
        Message<String> message = MessageBuilder.withPayload(jsonString).build();
        //发送一条事务消息
        /**
         * String txProducerGroup 生产组
         * String destination topic，
         * Message<?> message, 消息内容
         * Object arg 参数
         */
        rocketMQTemplate.sendMessageInTransaction("producer_group","topic_txmsg",message,null);
    }

    @Transactional
    @Override
    public void addOpt(Integer id,String TxNo,String ip) {

        //幂等判断
        if(optMapper.isExistTx(TxNo)>0){

            optMapper.changeTx(TxNo);
            return ;
        }



        OptInfo optInfo = new OptInfo();
        optInfo.setOpt(2);
        //操作的管理员
        AdminInfo admin = adminService.findById(id);
        optInfo.setAdminInfo(admin);
        optInfo.setIp(ip);
        optMapper.add(optInfo);

        //添加事务日志
        optMapper.addTx(TxNo);



    }
}
